package com.tiancheng.trade.order.mq.consumer;

import com.rabbitmq.client.Channel;
import com.tiancheng.trade.order.service.MessageSubscribeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author kellen
 * @description 取消订单消息的处理者
 * @date 2025/02/25 23:39
 */
@Component
@Slf4j
public class PaymentStatusMsgConsumer {

    @Resource
    private MessageSubscribeService messageSubscribeService;

    @RabbitListener(queues = "trade.payment.status")
    public void handMessage(String message, Channel channel,
                            @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        try {
            log.info("支付中心消息回调：{}", message);
            messageSubscribeService.handle(message);
            channel.basicAck(tag, false);
        } catch (Exception e) {
            log.error("消息处理异常：", e);
        } finally {
            try {
                // 消息处理失败，拒绝消息并重新入队
                channel.basicNack(tag, false, false);
            } catch (IOException ex) {
                log.error("确认消息失败", ex);
            }
        }
    }
}
